package com.huan.service.impl;


import com.huan.dao.mapper.TeacherMapper;
import com.huan.pojo.PageBean;

import com.huan.pojo.Teacher;
import com.huan.service.TeacherService;
import com.huan.util.SqlSessionFactoryUtils;

import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;

import java.util.List;

public class TeacherServiceImpl implements TeacherService {
    //1.创建工厂对象
    SqlSessionFactory factory = SqlSessionFactoryUtils.getSqlSessionFactory();


    @Override
    public PageBean<Teacher> selectByPageAndCondition(int currentPage, int pageSize, Teacher teacher) {
        SqlSession sqlSession = factory.openSession();
        TeacherMapper mapper = sqlSession.getMapper(TeacherMapper.class);

        //计算开始索引
        int begin = (currentPage - 1)*pageSize;
        //计算查询条目数
        int size = pageSize;

        String name = teacher.getName();

        if (name!=null&&name.length()>0){
            teacher.setName("%"+name+"%");
        }

        //查询当前页数据
        List<Teacher> rows = mapper.selectByPageAndCondition(begin, size, teacher);

        //查询总记录数
        int totalCount = mapper.selectTotalCountByCondition(teacher);

        //封装PageBean对象
        PageBean<Teacher> pageBean = new PageBean<>();
        pageBean.setRows(rows);
        pageBean.setTotalCount(totalCount);

        sqlSession.close();

        return pageBean;
    }


    @Override
    public boolean add(Teacher teacher) {
        SqlSession sqlSession = factory.openSession();
        TeacherMapper mapper = sqlSession.getMapper(TeacherMapper.class);
        boolean flag = mapper.add(teacher);
        sqlSession.commit();
        sqlSession.close();
        return flag;
    }

    @Override
    public int update(Teacher teacher) {
        SqlSession sqlSession = factory.openSession();
        TeacherMapper mapper = sqlSession.getMapper(TeacherMapper.class);
        int i = mapper.update(teacher);
        sqlSession.commit();
        sqlSession.close();
        return i;
    }

    @Override
    public void delete(String teacherID) {
        SqlSession sqlSession = factory.openSession();
        TeacherMapper mapper = sqlSession.getMapper(TeacherMapper.class);
        mapper.delete(teacherID);
        sqlSession.commit();
        sqlSession.close();
    }

    @Override
    public void deleteByIds(String[] ids) {
        SqlSession sqlSession = factory.openSession();
        TeacherMapper mapper = sqlSession.getMapper(TeacherMapper.class);
        mapper.deleteByIds(ids);
        sqlSession.commit();
        sqlSession.close();
    }
}
